<script setup lang="ts">
import { useRequest } from 'alova/client'
import { useRouter } from 'vue-router'
import { taskApi } from '@/service/api/bizhi'
import NoticeList from '../common/NoticeList.vue'

const router = useRouter()

// 重要任务数据
const importantTasks = ref<any[]>([])

// 获取重要任务
const { send: fetchImportantTasks } = useRequest(() => taskApi.getImportantTasks(), {
  immediate: false
})

// 加载重要任务
const loadImportantTasks = async () => {
  try {
    const response: any = await fetchImportantTasks()
    if (response.code === 200) {
      // 将任务转换为消息格式
      importantTasks.value = response.data.map((task: any) => ({
        id: `task_${task.id}`,
        type: 2, // 待办类型
        title: task.title,
        icon: 'icon-park-outline:checklist',
        tagTitle: task.priority === 'high' ? '高优先级' : task.priority === 'medium' ? '中优先级' : '低优先级',
        tagType: task.priority === 'high' ? 'error' : task.priority === 'medium' ? 'warning' : 'info',
        description: task.description ? task.description.substring(0, 50) + '...' : '暂无描述',
        date: new Date(task.created_at).toLocaleDateString('zh-CN'),
        isRead: false,
        taskId: task.id
      }))
    }
  } catch (error) {
    console.error('加载重要任务失败:', error)
  }
}

// 处理点击任务通知
function handleRead(id: number | string) {
  // 处理任务消息点击
  const taskData = importantTasks.value.find((i: any) => i.id === id)
  if (taskData && taskData.taskId) {
    // 跳转到任务管理页面，并传递任务ID参数
    router.push({
      path: '/task',
      query: { taskId: taskData.taskId }
    })
    return
  }

  // 如果不是任务消息，显示提示
  window.$message.info('点击了通知')
}

const massageCount = computed(() => {
  // 只统计重要任务的数量（未读状态）
  const taskCount = importantTasks.value.filter((i: any) => !i.isRead).length
  return taskCount
})

// 页面加载时获取重要任务
onMounted(() => {
  loadImportantTasks()

  // 定期刷新重要任务（每5分钟）
  setInterval(() => {
    loadImportantTasks()
  }, 5 * 60 * 1000)
})
</script>

<template>
  <n-popover placement="bottom" trigger="click" arrow-point-to-center class="!p-0">
    <template #trigger>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <CommonWrapper>
            <n-badge :value="massageCount" :max="99" style="color: unset">
              <icon-park-outline-remind />
            </n-badge>
          </CommonWrapper>
        </template>
        <span>{{ $t('app.notificationsTips') }}</span>
      </n-tooltip>
    </template>
    <div class="w-390px">
      <div class="flex items-center justify-center p-3 border-b border-gray-200">
        <n-space justify="center">
          {{ $t('app.todos') }}
          <n-badge type="error" :value="massageCount" :max="99" />
        </n-space>
      </div>
      <NoticeList :list="importantTasks" @read="handleRead" />
    </div>
  </n-popover>
</template>

<style scoped></style>
